import inspect
import time
from datetime import datetime
import os
from colorama import Fore
import functools
from config import DIR


def info(text):
    formatted_time = datetime.now().strftime('%H:%M:%S:%f')[:-3]
    stack = inspect.stack()
    code_path = f'{os.path.basename(stack[1].filename)}:{stack[1].lineno}'
    content = f'[Info]{formatted_time}-{code_path}>>{text}'
    print(Fore.LIGHTGREEN_EX + content)
    str_time = datetime.now().strftime("%Y%m%d")
    log_file = os.path.join(DIR, 'logs', f'{str_time}_info.log')
    with open(file=log_file, mode='a', encoding='utf-8') as f:
        f.write(content + '\n')

def error(text):
    formatted_time = datetime.now().strftime('%H:%M:%S:%f')[:-3]
    stack = inspect.stack()
    code_path = f'{os.path.basename(stack[1].filename)}:{stack[1].lineno}'
    content = f'[error]{formatted_time}-{code_path}>>{text}'
    print(Fore.LIGHTCYAN_EX + content)
    str_time = datetime.now().strftime("%Y%m%d")
    # 将error log 写入 info.log文件，确保log的完整性
    log_file = os.path.join(DIR, 'logs', f'{str_time}_info.log')
    with open(file=log_file, mode='a', encoding='utf-8') as f:
        f.write(content + '\n')
    # 将 error 单独写入 error log，便于查看error 信息
    log_file = os.path.join(DIR, 'logs', f'{str_time}_error.log')
    with open(file=log_file, mode='a', encoding='utf-8') as f:
        f.write(content + '\n')

def email_send_decoration(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            # 假设 args[0] 是 self，从实例中获取一些信息
            if len(args) > 0 and hasattr(args[0], 'sender'):
                sender = args[0].sender
            else:
                sender = "未知发件人"
            if len(args) > 0 and hasattr(args[0], 'recipients'):
                recipients = args[0].recipients
            else:
                recipients = ["未知收件人"]
            recipient_str = ", ".join(recipients)

            info(f"开始发送邮件，发件人: {sender}，收件人: {recipient_str}")
            result = func(*args, **kwargs)
            end = time.perf_counter()
            handle_time = end - start
            info(f"邮件发送完成，耗时: {handle_time:.2f} 秒")
            return result
        except Exception as e:
            error(f"邮件发送出错: {str(e)}")
            end = time.perf_counter()
            handle_time = end - start
            error(f"邮件发送失败，耗时: {handle_time:.2f} 秒")
            return None

    return wrapper

def class_email_send_decoration(cls):
    """用例的日志类级别装饰器，用于自动为类中以 send_emails 开头的方法应用 email_send_decoration 装饰器"""
    # 获取类中所有的成员方法
    for name, method in inspect.getmembers(cls, inspect.isfunction):
        if name.startswith('send_emails'):
            # 只对以 send_emails 开头 的方法进行装饰
            setattr(cls, name, email_send_decoration(method))
    return cls
